package com.puman.watchtrade.fragment.set;

import java.util.Set;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.puman.watchtrade.MainActivity;
import com.puman.watchtrade.R;
import com.puman.watchtrade.fragment.LeftCategoryFragment;
import com.puman.watchtrade.fragment.set.httpHandler.SettingHttpHandler;
import com.puman.watchtrade.util.DataResult;
import com.puman.watchtrade.util.Gjfun;
import com.puman.watchtrade.util.GlobalData;
import com.puman.watchtrade.util.LoadingProgressDialog;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint({ "ValidFragment", "NewApi" })
public class LoginFragment extends Fragment implements OnClickListener {
	private View mView;

	private EditText mobile;
	private EditText password;
	private static final int LOGIN_SUC = 0x1;
	private static final int LOGIN_FAIL = 0x2;
	private DataResult dataResult = new DataResult();
	private SettingHttpHandler settingHttpHandler = new SettingHttpHandler();
	private ImageView selectIcon;
	private LoadingProgressDialog mProgress = null;

	RelativeLayout topBgLayout;

	/*
	 * variable
	 */
	private boolean isRemember = true;
	private SharedPreferences sharedPreferences; // 私有数据
	private Editor editor;

	public LoginFragment() {
		super();
	}

	public LoginFragment(String flag) {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.login_layout, null);
		initView();
		return mView;
	}

	private void initView() {
		sharedPreferences = MainActivity.getInstant().getSharedPreferences(
				"watchtrade", Context.MODE_PRIVATE);
		editor = sharedPreferences.edit();// 获取编辑器

		topBgLayout = (RelativeLayout) mView.findViewById(R.id.personal_topBg);

		mView.findViewById(R.id.login_layout).setOnClickListener(this);

		mView.findViewById(R.id.main_left_imgbtn).setOnClickListener(
				MainActivity.getInstant().mySetOnClickListener);
		mView.findViewById(R.id.login_register_btn).setOnClickListener(this);
		mView.findViewById(R.id.login_login_btn).setOnClickListener(this);
		mView.findViewById(R.id.login_forgetpass).setOnClickListener(this);

		mobile = (EditText) mView.findViewById(R.id.login_mobile_input);
		password = (EditText) mView.findViewById(R.id.login_pass_input);

		mobile.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					topBgLayout.setVisibility(View.GONE);
				} else {
					topBgLayout.setVisibility(View.VISIBLE);
				}
			}
		});

		password.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					topBgLayout.setVisibility(View.GONE);
				} else {
					topBgLayout.setVisibility(View.VISIBLE);
				}
			}
		});
		mobile.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (!sharedPreferences.getString(s.toString(), "").equals("")) {
					password.setText(sharedPreferences.getString(s.toString(),
							""));
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});

		mView.findViewById(R.id.login_remember_pass).setOnClickListener(this);
		selectIcon = (ImageView) mView
				.findViewById(R.id.login_remember_pass_icon);
		selectRem();
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) v.getContext()
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
		}
		FragmentTransaction transaction = MainActivity.fragmentManager
				.beginTransaction();
		switch (v.getId()) {
		case R.id.main_left_imgbtn:
			MainActivity.getInstant().fragmentManager.popBackStack();
			break;
		case R.id.login_register_btn:
			RegisterFragment registerFragment = new RegisterFragment();
			transaction.replace(R.id.main_non_bottom, registerFragment);
			transaction.addToBackStack(null);
			transaction.commit();
			break;
		case R.id.login_login_btn:
//			if (!Gjfun.isPhoneNumberValid(mobile.getText().toString())) {
//				Toast.makeText(getActivity(), "手机无效", Toast.LENGTH_LONG).show();
//				break;
//			}
			if (checkValidate()) {
				login();
			}
			break;
		case R.id.login_forgetpass:
			ForgetPassFragment forgetPassFragment = new ForgetPassFragment();
			transaction.replace(R.id.main_non_bottom, forgetPassFragment);
			transaction.addToBackStack(null);
			transaction.commit();
			break;
		case R.id.login_remember_pass:
			isRemember = !isRemember;
			selectRem();
			break;
		case R.id.login_layout:
			if (imm.isActive()) {
				imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
			}
			topBgLayout.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}

	}

	/*
	 * 选择是否记住密码
	 */
	private void selectRem() {

		if (isRemember) {

			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
				selectIcon.setBackground(MainActivity.getInstant()
						.getResources()
						.getDrawable(R.drawable.login_remenber_select));
			} else {
				selectIcon.setBackgroundDrawable(MainActivity.getInstant()
						.getResources()
						.getDrawable(R.drawable.login_remenber_select));
			}
		} else {
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
				selectIcon.setBackground(MainActivity.getInstant()
						.getResources()
						.getDrawable(R.drawable.login_forget_unselect));
			} else {
				selectIcon.setBackgroundDrawable(MainActivity.getInstant()
						.getResources()
						.getDrawable(R.drawable.login_forget_unselect));
			}

		}
	}

	/*
	 * 登录
	 */
	private void login() {
		mProgress = Gjfun.startProgressDialog(mProgress, getActivity());
		MainActivity.getInstant().cachedThreadPoolMinPriority
				.execute(resetRunnable);
	}

	/*
	 * 登录
	 */
	Runnable resetRunnable = new Runnable() {

		@Override
		public void run() {
			int what = LOGIN_FAIL;
			dataResult = null;
			dataResult = new DataResult();
			dataResult = settingHttpHandler.login(mobile.getText().toString(),
					password.getText().toString());
			if (dataResult.flag) {
				what = LOGIN_SUC;
			}
			sendMessage(what);
		}
	};

	Callback callback = new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			Gjfun.stopProgressDialog(mProgress);
			switch (msg.what) {
			case LOGIN_SUC:
				Toast.makeText(MainActivity.getInstant(), "" + dataResult.msg,
						Toast.LENGTH_SHORT).show();
				if (GlobalData.userInfo != null) {
					if (!GlobalData.userInfo.getNick().equals("")) {
						LeftCategoryFragment.userName
								.setText(GlobalData.userInfo.getNick());
					} else {
						LeftCategoryFragment.userName
								.setText(GlobalData.userInfo.getMobile());
					}
					LeftCategoryFragment.loginBtnInfo.setText("退出");
				}
				
				editor.putString("mobile",mobile.getText().toString());
				editor.putString("password",password.getText().toString());
				
				if (isRemember) {
					editor.putString(mobile.getText().toString(), password
							.getText().toString());
//					editor.commit();
				} else {
					editor.putString(mobile.getText().toString(), "");
//					editor.commit();
				}
				editor.commit();
				MainActivity.getInstant().registerAlisePush();
				// 提交修改
				MainActivity.getInstant().fragmentManager.popBackStack();
				break;
			case LOGIN_FAIL:
				Toast.makeText(MainActivity.getInstant(), "" + dataResult.msg,
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
			return false;
		}
	};
	Handler handler = new Handler(callback);

	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	private boolean checkValidate() {
		if (password.getText().toString().length() < 6
				|| password.getText().toString().length() > 18) {
			Toast.makeText(MainActivity.getInstant(), "请输入6-18位密码",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;

	}

	

}
